<?php

class PopularPostsWidget extends WP_Widget {

	function __construct(){
		$widget_ops = array('classname' => 'widget_popular_posts',
							'description' => __('Display popular posts', 'GIFPark'));
		$this->WP_Widget('PopularPostsWidget', __('WPTeam | Popular posts', 'GIFPark'), $widget_ops);
	}

	public function form($instance){
		$instance = wp_parse_args((array) $instance, array('count' => 7));
		?>
			<label for='<?php echo $this->get_field_id('wtitle'); ?>'><?php _e('Widget title', 'GIFPark'); ?></label> 
			<input style="float:right; width: 100%" id='<?php echo $this->get_field_id('wtitle'); ?>' name='<?php echo $this->get_field_name('wtitle'); ?>' type='text' value="<?php echo attribute_escape($instance['wtitle']); ?>"/>
			<br/>
			<label for='<?php echo $this->get_field_id('count'); ?>'><?php _e('Posts number', 'GIFPark'); ?></label> 
			<input style="float:right; width: 100%" id='<?php echo $this->get_field_id('title'); ?>' name='<?php echo $this->get_field_name('count'); ?>' type='text' value="<?php echo attribute_escape($instance['count']); ?>"/>
			<br/><br/>
		<?php
	}

	public function update($new_instance, $old_instance){
		$instance = $old_instance;
		$instance['count'] = $new_instance['count'];
		$instance['wtitle'] = $new_instance['wtitle'];
		return $instance;
	}
	
	public function widget($args, $instance){
		extract($args, EXTR_SKIP);
		echo $before_widget;
		echo $before_title . $instance['wtitle'] . $after_title;
		?>
			<ul class="menu">
			<?php 
				$args = array(
					'numberposts'	=>	(int)$instance['count'],
					'orderby'		=>	'comment_count',
					'order'			=>	'DESC',
					'post_type'		=>	'post',
					'post_status'	=>	'publish',
				);
				$posts_array = get_posts( $args );
				foreach ($posts_array as $post): ?>
					<li>
						<a class="widget_image" href="<?php echo get_permalink($post->ID); ?>" title="<?php echo $post->post_title; ?>">
							<?php if ( has_post_thumbnail($post->ID) ) {
								echo get_the_post_thumbnail($post->ID, 'thumb-size-1',
									array('class' => 'sidebar_img', 'title' => get_the_title($post->ID), 'alt' => $post->post_title)
								);
							} else { ?>
								<img src="<?php echo get_template_directory_uri(); ?>/images/news/1.png" alt="<?php echo $post->post_title; ?>"/>
							<?php } ?></a>
						<a href="<?php echo get_permalink($post->ID); ?>" title="<?php echo $post->post_title; ?>" class="title"><?php echo $post->post_title; ?></a>
						<p><?php get_substr($post->post_content)?></p>
						<span class="arrow"></span>
					</li>
					<?php 
				endforeach;
				wp_reset_query();
			?>
			</ul>
		<?php
		echo $after_widget;
	}
}